package com.study.rcp.framework.core; 
 
import java.io.PrintStream; 
 
import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.graphics.Font;
import org.eclipse.ui.console.ConsolePlugin; 
import org.eclipse.ui.console.IConsole; 
import org.eclipse.ui.console.IConsoleManager; 
import org.eclipse.ui.console.MessageConsole; 
import org.eclipse.ui.console.MessageConsoleStream; 
 
public class ConsoleFactory { 
	private static final SimpleDateFormat sdf = new SimpleDateFormat("MM-dd hh:mm:ss");//时间格式
	/**
	 * 将信息输出到控制台
	 * %d{MMdd HHmmss SSS}[%-5p] %m%n
	 * */
	public void print(String str) {
		ConsoleFactory.info(sdf.format(new Date()) + "[INFO] " + str);
	}
    public static MessageConsole console = new MessageConsole( 
            "操作日志", null); 
 
    public void openConsole() { 
        showConsole(); 
    } 
 
    public static void showConsole() { 
        if (console != null) { 
            IConsoleManager manager = ConsolePlugin.getDefault() 
                    .getConsoleManager(); 
            IConsole[] existing = manager.getConsoles(); 
            boolean exists = false; 
            for (int i = 0; i < existing.length; i++) { 
                if (console == existing[i]) 
                    exists = true; 
            } 
            if (!exists) { 
                manager.addConsoles(new IConsole[] { console }); 
            } 
            manager.showConsoleView(console); 
            Font boldFont = JFaceResources.getFontRegistry().defaultFont();//.getBold(JFaceResources.DEFAULT_FONT);
            console.setFont(boldFont);
            MessageConsoleStream stream = console.newMessageStream(); 
            System.setOut(new PrintStream(stream)); 
        } 
    } 
 
    public static void closeConsole() { 
        IConsoleManager manager = ConsolePlugin.getDefault() 
                .getConsoleManager(); 
        if (console != null) { 
            manager.removeConsoles(new IConsole[] { console }); 
        } 
    } 
 
    public static MessageConsole getConsole() { 
        return console; 
    } 
    
    public static void info(String str){
    	MessageConsoleStream  printer = console.newMessageStream();   
        ConsoleFactory.showConsole();   
        printer.print(sdf.format(new Date()) + "[INFO] " + str+"\n"); 
    }
    
} 
